package com.wq.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wq.common.BaseContext;
import com.wq.common.R;
import com.wq.entity.AddressBook;
import com.wq.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @ description
 * @ author wuyunpeng
 * @ create 2022-07-24 10:43
 */
@RestController
@Slf4j
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    AddressBookService addressBookService;

    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook) {
        final Long userID = BaseContext.getCurrentID();
        addressBook.setUserId(userID);
        addressBookService.save(addressBook);
        return R.success("添加地址成功");
    }

    @GetMapping("/list")
    public R<List<AddressBook>> list() {
        final Long userID = BaseContext.getCurrentID();
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(userID != null, AddressBook::getUserId, userID);
        lqw.orderByDesc(AddressBook::getUpdateTime);
        final List<AddressBook> addressBookList = addressBookService.list(lqw);
        return R.success(addressBookList);
    }

    @PutMapping("/default")
    public R<String> setDefault(@RequestBody AddressBook addressBook) {
        LambdaUpdateWrapper<AddressBook> luw = new LambdaUpdateWrapper<>();
        final Long userID = BaseContext.getCurrentID();
        luw.eq(AddressBook::getUserId, userID);
        luw.set(AddressBook::getIsDefault, 0);
        addressBookService.update(luw);

        /**
         * address 中为 null 的字段不会修改
         */
        final Long id = addressBook.getId();
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return R.success("设置默认地址成功");
    }

    @GetMapping("/default")
    public R<AddressBook> getDefault() {
        final Long userID = BaseContext.getCurrentID();
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId, userID);
        lqw.eq(AddressBook::getIsDefault, 1);
        final AddressBook defaultAddress = addressBookService.getOne(lqw);
        return R.success(defaultAddress);
    }
}
